package main

import (
	"fmt"
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type Config struct {
	Global        map[string]interface{}   `yaml:"global"`
	RemoteWrite   []map[string]interface{} `yaml:"remote_write"`
	ScrapeConfigs []map[string]interface{} `yaml:"scrape_configs"`
}

type Target struct {
	Targets []string          `yaml:"targets"`
	Labels  map[string]string `yaml:"labels"`
}

func main() {
	// 读取文件
	data, err := ioutil.ReadFile("E:\\application\\开发环境归档\\omc-prometheus-collector\\overlays\\tempnode\\tempregion\\omc-prometheus-collector-0.yaml")
	if err != nil {
		panic(err)
	}

	// 解析YAML
	var config Config
	err = yaml.Unmarshal(data, &config)
	if err != nil {
		panic(err)
	}

	// 根据job_name插入指定数据
	for i, scrapeConfig := range config.ScrapeConfigs {
		if scrapeConfig["job_name"] == "ipmi" {
			newTarget := map[string]interface{}{
				"targets": []string{"10.254.4.94"},
				"labels": map[string]string{
					"cpu_arch": "x86",
					"password": "Password@_",
					"instance": "bms6900",
					"zone":     "cn-beijing-a",
					"vendor":   "h3c",
					"bmc_ip":   "10.254.4.94",
					"id":       "7040892710249385984",
					"region":   "cn-beijing",
					"group":    "ubm",
					"username": "admin",
				},
			}
			s := scrapeConfig["static_configs"].([]interface{})
			m := make([]interface{}, len(s)+1)
			for j, v := range s {
				m[j] = v.(map[interface{}]interface{})
			}
			m[len(s)] = newTarget
			config.ScrapeConfigs[i]["static_configs"] = m
		}
	}

	// 将修改后的配置写回文件
	newData, err := yaml.Marshal(&config)
	if err != nil {
		panic(err)
	}
	err = ioutil.WriteFile("./demo.yaml", newData, 0644)
	if err != nil {
		panic(err)
	}

	fmt.Println("Done!")
}
